// 引入API工具类
const api = require('./utils/api.js');

App({
  globalData: {
    // 用户信息
    userInfo: null,
    token: null,
    
    // 蓝牙相关
    bluetoothEnabled: false,
    deviceConnected: false,
    deviceId: '',
    serviceId: 'FEE0',
    writeCharacteristicId: 'FEE2', 
    notifyCharacteristicId: 'FEE4',
    
    // 治疗参数
    treatmentParams: {
      mode: 'tDCS+', // tDCS+, tDCS-, tACS
      current: 1.0, // 0-2 mA
      time: 20, // 分钟
      frequency: 10.0 // 0.1-100 Hz
    },
    
    // 设备状态
    deviceStatus: {
      working: false,
      paused: false,
      battery: 100,
      remainingTime: 0
    }
  },

  onLaunch() {
    // 初始化本地存储
    // this.initLocalStorage();
    
    // 检查蓝牙状态
    this.checkBluetoothState();
    
    // 自动登录
    this.autoLogin();
  },

  /**
   * 自动登录
   */
  async autoLogin() {
    try {
        
      // 如果没有token，尝试微信登录
      await this.wechatLogin();
    } catch (error) {
      console.error('自动登录失败:', error);
      // 即使登录失败，也要初始化本地数据
      this.initDefaultData();
    }
  },

  /**
   * 微信登录
   */
  async wechatLogin() {
    
    return new Promise((resolve, reject) => {
      // 获取微信登录凭证
      wx.login({
        success: async (res) => {
          if (res.code) {
            
            try {
              // 获取用户信息
              const userInfo = await this.getUserInfo();
              
              // 调用后端登录接口
              let loginData = await api.wechatLogin(res.code, userInfo);
              loginData = loginData.data
              // 保存用户信息和token
              this.globalData.userInfo = loginData.user;
              this.globalData.token = loginData.access_token;
              api.setToken(loginData.access_token);
              
              // 保存到本地存储
              wx.setStorageSync('userInfo', loginData.user);
              wx.setStorageSync('token', loginData.access_token);
              
              console.log('微信登录成功', loginData.user);
              resolve(loginData);
              resolve(loginData.data);
            } catch (error) {
              console.error('登录接口调用失败:', error);
              // 如果是用户不存在的错误，后端会自动创建用户
              // 我们可以尝试重新登录一次
              if (error.message && error.message.includes('用户不存在')) {
                try {
                  // 重新调用登录接口，此时用户应该已经创建
                  const retryLoginData = await api.wechatLogin(res.code, userInfo);
                  
                  // 保存用户信息和token
                  this.globalData.userInfo = retryLoginData.user;
                  this.globalData.token = retryLoginData.access_token;
                  api.setToken(retryLoginData.access_token);
                  
                  // 保存到本地存储
                  wx.setStorageSync('userInfo', retryLoginData.user);
                  wx.setStorageSync('token', retryLoginData.access_token);
                  
                  console.log('微信登录成功（重试）', retryLoginData.user);
                  resolve(retryLoginData);
                } catch (retryError) {
                  console.error('重试登录失败:', retryError);
                  reject(retryError);
                }
              } else {
                reject(error);
              }
            }
          } else {
            console.error('登录失败！' + res.errMsg);
            reject(new Error('获取微信登录凭证失败'));
          }
        },
        fail: (err) => {
          console.error('微信登录失败:', err);
          reject(err);
        }
      });
    });
  },

  /**
   * 获取用户信息
   */
  getUserInfo() {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: '用于完善用户资料',
        success: (res) => {
          resolve({
            nickName: res.userInfo.nickName,
            avatarUrl: res.userInfo.avatarUrl,
            gender: res.userInfo.gender,
            province: res.userInfo.province,
            city: res.userInfo.city,
            country: res.userInfo.country
          });
        },
        fail: () => {
          // 如果用户拒绝授权，使用默认信息
          resolve({
            nickName: '匿名用户',
            avatarUrl: ''
          });
        }
      });
    });
  },

  /**
   * 初始化本地存储
   */
  initLocalStorage() {
    // 初始化治疗记录
    if (!wx.getStorageSync('treatmentRecords')) {
      wx.setStorageSync('treatmentRecords', []);
    }
    
    // 初始化用户参数模板
    if (!wx.getStorageSync('userTemplates')) {
      wx.setStorageSync('userTemplates', [
        {
          id: 1,
          name: '默认模式',
          mode: 'tDCS+',
          current: 1.0,
          time: 20,
          frequency: 10.0
        }
      ]);
    }
  },

  /**
   * 初始化默认数据（当登录失败时使用）
   */
  initDefaultData() {
    // 从本地存储获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    const token = wx.getStorageSync('token');
    
    if (userInfo && token) {
      this.globalData.userInfo = userInfo;
      this.globalData.token = token;
    } else {
      // 使用本地默认数据
      this.globalData.userInfo = {
        id: 0,
        nickname: '匿名用户',
        avatar_url: ''
      };
    }
  },

  checkBluetoothState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        this.globalData.bluetoothEnabled = res.available;
      },
      fail: () => {
        this.globalData.bluetoothEnabled = false;
      }
    });
  },

  // 保存治疗记录
  async saveTreatmentRecord(params, duration, deviceId) {
    const records = wx.getStorageSync('treatmentRecords') || [];
    const record = {
      id: Date.now(),
      date: new Date().toISOString(),
      duration: duration, // 实际治疗时长(分钟)
      deviceId: deviceId || this.globalData.deviceId || 'unknown', // 保存设备ID
      params: { ...params },
      completed: duration >= params.time * 0.8 // 完成度80%以上算完成
    };
    
    records.unshift(record);
    // 只保留最近100条记录
    if (records.length > 100) {
      records.splice(100);
    }
    
    wx.setStorageSync('treatmentRecords', records);
    
    // 如果用户已登录，同时保存到服务器
    if (this.globalData.token) {
      try {
        const now = new Date();
        const startTime = new Date(now.getTime() - duration * 60000);
        const formatDateTime = (date) => {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          const seconds = String(date.getSeconds()).padStart(2, '0');
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        };
        await api.createTreatmentRecord({
          device_id: deviceId || this.globalData.deviceId || 'unknown',
          treatment_mode: params.mode,
          current_intensity: params.current,
          treatment_duration: params.time,
          frequency: params.frequency,
          start_time: formatDateTime(startTime),
          end_time: formatDateTime(now),
          status: record.completed ? 'completed' : 'interrupted',
          notes: '小程序记录'
        });
        console.log('治疗记录已同步到服务器');
      } catch (error) {
        console.error('治疗记录同步失败:', error);
      }
    }
  }
});